﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PBOffice.DAL;
using System.Data.Entity;
using System.Data;

namespace PBOffice.BLL
{
   public class LoginBLL
    {
        #region 判断登陆
        /// <summary>
        /// 判断登陆是否成功。成功返回true，否则返回false
        /// </summary>
        /// <param name="userId">用户帐号</param>
        /// <param name="userPwd">用户密码</param>
        /// <returns>bool类型，成功返回true，否则返回false</returns>
        public static bool UserLogin(string userId, string userPwd)
        {
            bool b = false;
            //根据帐号密码查询数据
            using (MyOfficeEntities MyofficeDB = new MyOfficeEntities())
            {
                var users = from user in MyofficeDB.Users
                            where user.UserId == userId && user.UserPwd == userPwd
                            select user;
                if (users.Count() > 0)
                {
                    b = true;
                }
            }
            return b;
        } 
        #endregion

        #region 根据帐号密码查询员工的信息。返回list泛型集合
        /// <summary>
        /// 根据帐号密码查询员工的信息。返回list泛型集合
        /// </summary>
        /// <param name="userID">帐号</param>
        /// <param name="userPwd">密码</param>
        /// <returns></returns>
        public static User SelectUserManageByUserIdAndUserPwd(string userID, string userPwd)
        {
            using (MyOfficeEntities myoffice = new MyOfficeEntities())
            {
                var user = from v in myoffice.Users
                           where v.UserPwd == userPwd && v.UserId == userID
                           select v;
                return user.SingleOrDefault();
            }
        } 
        #endregion

        #region 添加登陆日志
        /// <summary>
        /// 添加登陆日志
        /// </summary>
        /// <param name="listUser">用户的信息集合</param>
        /// <param name="Logintime">登陆时间</param>
        /// <param name="ip">登陆IP</param>
        public static void AddLoginLogs(User listUser, DateTime Logintime, string ip)
        {
            using (MyOfficeEntities myoffice = new MyOfficeEntities())
            {
                int userNo = Convert.ToInt32(listUser.UserNo.ToString());
                //获取数据
                var loginlogs = myoffice.LoginLogs.CreateObject();//把loginlogs表转换为object类型
                //因为实体类模型的关系这里获取user编号的时候麻烦了点
                //要根据参数的ID先找到在user表中的这条记录，在赋值给loginlogs表
                loginlogs.User = myoffice.Users.SingleOrDefault(user => user.UserNo == userNo);
                loginlogs.LoginTime = Logintime;
                loginlogs.LoginIP = ip;
                loginlogs.IsLogin = "是";
                loginlogs.LoginMemo = "登陆成功";
                //将数据添加
                myoffice.LoginLogs.AddObject(loginlogs);
                //将数据保存到数据库
                myoffice.SaveChanges();

            }
        } 
        #endregion

    }
}
